import re

from rest_framework import serializers
from users.models import User


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
            },
            'password': {
                'write_only': True,  # write_only表示该字段只参与反序列化过程（保存验证过程）
                'max_length': 20,
                'min_length': 8,
                # 'request':False
            }
        }
    def validate_mobile(self, value):
        if not re.match('1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机格式不正确')
        return value

    def create(self, validated_data):
        #1. 调用父类
        admin=super().create(validated_data)
        # 2.密码加密
        admin.set_password(validated_data['password'])
        admin.is_staff=True
        admin.save()
        # 3.结果返回
        return admin